/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.plan.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.store.dao.MaterialsBatchDetailDAO;
import com.javaeye.plan.dao.MonthPlanDAO;
import com.javaeye.plan.dto.MonthPlanDetail;
import com.javaeye.store.dto.MaterialsBatchDetail;

public class MonthPlanService implements IMonthPlanService {
	
	private static Log log = LogFactory.getLog(MonthPlanService.class);
	
	private MonthPlanDAO dao;
	
	private MaterialsBatchDetailDAO materialsBatchDetailDao;
	
	public void setDao(MonthPlanDAO dao) {
		this.dao = dao;
	}
	
	public void setMaterialsBatchDetailDao(
			MaterialsBatchDetailDAO materialsBatchDetailDao) {
		this.materialsBatchDetailDao = materialsBatchDetailDao;
	}

	public void saveMonthPlanList(List<MonthPlanDetail> planDetails, String[] removeDetailIds) {
		for (MonthPlanDetail detail : planDetails) {
			detail.setStatus(MONTH_PLAN_STATUS_CREATE);
			dao.saveMonthPlan(detail);
			
			//更新批次计划数量
			MaterialsBatchDetail batchDetail = materialsBatchDetailDao.getBatchDetail(
				detail.getProductId(), detail.getBatchNo());
			if (batchDetail == null) {
				batchDetail = new MaterialsBatchDetail();
				batchDetail.setMaterialsId(detail.getProductId());
				batchDetail.setBatchNo(detail.getBatchNo());
				batchDetail.setPlanNumber(detail.getNumber());
			} else {
				batchDetail.setPlanNumber(detail.getNumber());
			}
			materialsBatchDetailDao.save(batchDetail);
		}
		if (removeDetailIds != null) {
			for (String removeId : removeDetailIds) {
				if (!"".equals(removeId.trim())) {
					dao.deleteMonthPlan(Integer.parseInt(removeId));
				}
			}
		}
	}
	
	public List<MonthPlanDetail> getPlanDetailInfo(String dateNo) {
		//String queryDate = DateUtils.formatString(date, "yyyyMM");
		List<MonthPlanDetail> result = dao.getPlanDetailInfo(dateNo);
		if (result == null || result.size() == 0) {
			log.warn("未找到对于月份(" + dateNo + ")的计划单");
		}
		return result;
	}
}
